package config

import (
	"github.com/bbangert/toml"
	"github.com/golang/glog"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"os"
	"syscall"
)

type ProxyConfig struct {
	DB struct {
		Addr string
		ProxyAddr string
	}
	Server struct{
		LISTEN_PORT  int
		GOAL_PORT int
	}
	Mongodb struct{
		DB string
		HOST string
	}
}
type MiddleState struct{
	IsBuildModel bool `bson:"isBuildModel"''`
}

var file = "../proxy.conf"
var conn *mgo.Database
// proxy server config struct
func ReadConfig() (pc ProxyConfig) {
	if _, err := os.Stat(file); os.IsNotExist(err) {
		glog.Errorln(err)
		os.Exit(int(syscall.ENOENT))
	}

	if _, err := toml.DecodeFile(file, &pc); err != nil {
		glog.Fatalln(err)
	}


	return pc
}
func ConnectToDB() *mgo.Database{
	if conn==nil{
		Pc:= ReadConfig()
		session, err := mgo.Dial(Pc.Mongodb.HOST)
		if err != nil {
			panic(err)
		}
		//defer session.Close()
		session.SetMode(mgo.Monotonic, true)
		conn = session.DB(Pc.Mongodb.DB)
	}
	return conn
}

func OnRemember()bool{
	conn = ConnectToDB()
	c := conn.C("middle_state")
	result :=MiddleState{}
	c.Find(bson.M{}).One(&result)
	return result.IsBuildModel
}